#include "mainobject.h"
#include <QTimer>
#include <QSettings>

extern QString etherPortName;

mainObject::mainObject()
{
    QSettings settings("HKEY_CURRENT_USER\\Software\\sanwei",QSettings::NativeFormat);
    etherPortName = settings.value("port").toString();
    settings.deleteLater();

    udp = new myUDP;
    udp->start();
    connect(udp, SIGNAL(startOrStop(bool)), this, SLOT(startSMV(bool)));

    smv = new smvProcess;
    smv->run_mode = smvProcess::TIME;
    smv->start();
    connect(smv, SIGNAL(samplesIsReady()), this, SLOT(zeroSmpcntIsComing()));

    QTimer *taskTimer = new QTimer;
    taskTimer->start(200);
    connect(taskTimer, SIGNAL(timeout()), this, SLOT(sendResult()));

    resultIsReady = false;
}

void mainObject::startSMV(bool flag)
{
    qDebug()<<"to start?"<<flag;

    if(flag)
    {
        if(!smv->isOpen()) smv->start();

        smv->setReopen(smvProcess::TIME);

        if(!smv->isOpen())
        {
            udp->sendResult("ERROR",5);
        }
    }
    else
    {
        smv->run_mode = smvProcess::NOOP;
        smv->setClose();
    }
}

void mainObject::zeroSmpcntIsComing()
{
    resultIsReady = true;
}

void mainObject::sendResult()
{
    if(resultIsReady)
    {
        smv->test_result.flag = 'a';
        smv->test_result.de_name[0] = 's';
        smv->test_result.de_name[1] = 'a';
        smv->test_result.de_name[2] = 'n';
        smv->test_result.de_name[3] = 'w';
        smv->test_result.de_name[4] = 'e';
        smv->test_result.de_name[5] = 'i';

        smv->test_result.error_1 = (double)smv->test_result.error_1 / smv->test_result.total * 10000;
        smv->test_result.error_2 = (double)smv->test_result.error_2 / smv->test_result.total * 10000;
        smv->test_result.error_4 = (double)smv->test_result.error_4 / smv->test_result.total * 10000;
        smv->test_result.error_6 = (double)smv->test_result.error_6 / smv->test_result.total * 10000;

        char *ch = (char*)&(smv->test_result);

        udp->sendResult(ch, sizeof(smv->test_result));
        resultIsReady = false;

        qDebug()<<"send done!";
    }
}
